package me.yushuai.wukong.base.controller;

import io.minio.errors.MinioException;
import me.yushuai.wukong.base.api.AttachmentApi;
import me.yushuai.wukong.base.api.dto.PagingSearchAttachment;
import me.yushuai.wukong.base.api.vo.AttachmentVo;
import me.yushuai.wukong.base.entity.Attachment;
import me.yushuai.wukong.base.service.AttachmentService;
import me.yushuai.wukong.common.dto.PageDTO;
import me.yushuai.wukong.common.exceptin.DuplicateBizIdException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.stream.Collectors;

/**
 * 附件管理控制器
 *
 * @author zhoushuai@189.cn
 * @since 2023-09-19
 */
@RestController
public class AttachmentController implements AttachmentApi {

    private final AttachmentService attachmentService;

    @Autowired
    public AttachmentController(AttachmentService attachmentService) {
        this.attachmentService = attachmentService;
    }

    @Override
    public Long createAttachment(MultipartFile multipartFile) throws DuplicateBizIdException {
        try {
            this.attachmentService.uploadFile(multipartFile);
        } catch (MinioException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public PageDTO<AttachmentVo> page(PagingSearchAttachment request) {
        final PageDTO<Attachment> page = this.attachmentService.page(request);
        return PageDTO.of(page, page.getData()
                .stream()
                .map(v -> new AttachmentVo())
                .collect(Collectors.toList())
        );
    }
}
